import { observable, action, computed } from 'mobx'

class CartStore {
    @observable apples = [
        {
            id: 0,
            weight: 233,
            isEaten: false
        },
        {
            id: 1,
            weight: 235,
            isEaten: true
        },
        {
            id: 2,
            weight: 256,
            isEaten: false
        }
    ];
    @observable newAppleId = 3;
    @observable isPicking = false;
    @observable buttonText = '摘苹果';

    /*摘苹果的异步操作*/
    @action pickApple = () => {
        /** 如果正在摘苹果，则结束这个thunk, 不执行摘苹果 */
        if (this.isPicking) {
            return;
        }
        this.isPicking = true;
        this.buttonText = '正在采摘...';
        setTimeout(() => {
            let weight = Math.floor(200 + Math.random() * 50);
            this.buttonText = '摘苹果';
            this.apples.push({
                id: this.newAppleId,
                weight: weight,
                isEaten: false
            });
            this.newAppleId++
        }, 1000);
        this.isPicking = false;
    }

    /*计算当前已吃和未吃苹果状态*/
    @computed get status () {
        let status = {
            appleNow: {
                num: 0,
                weight: 0
            },
            appleEaten: {
                num: 0,
                weight: 0
            }
        }
        this.apples.forEach(apple => {
            let selector = apple.isEaten ? 'appleEaten' : 'appleNow'
            status[selector].num++
            status[selector].weight += apple.weight
        })
        return status
    }

    @computed get applesList () {
        return this.apples.filter(app => !app.isEaten)
    }

    @action eatApple = (id) => {
        this.apples.find(app => app.id === id).isEaten = true
    }
}
export default CartStore